<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="">
          <el-input
              v-model="searchInfo.serviceName"
              placeholder="请输入服务代理名称"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit"
          >查询</el-button
          >
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addService"
        >新增</el-button
        >
      </div>
      <el-table
          :data="sortedData"
          row-key="ServiceId"
          @sort-change="sortChange"
      >
        <el-table-column
            align="left"
            label="序号"
            min-width="80"
            type="index"
        />
        <el-table-column
            align="left"
            label="服务代理名称"
            min-width="120"
            prop="ServiceName"
        />
        <el-table-column
            align="left"
            label="程序Url"
            min-width="150"
            prop="VisitUrl"
        />
        <el-table-column
            align="left"
            label="代理类别"
            min-width="100"
            prop="ServiceType"
        />
        <el-table-column align="left" label="当前状态">
          <template #default="scope">
            <span>{{ scope.row.Status === 1 ? '正常' : '停用' }}</span>
          </template>
        </el-table-column>
        <el-table-column
            align="left"
            label="运行路径"
            min-width="100"
            prop="ServiceExecDir"
        />
        <el-table-column align="left" label="程序版本号" prop="ServiceVersion"  width="200"/>
        <el-table-column align="left" label="服务代理配置" min-width="150">
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="goToconfigure(scope.row.ServiceId)"
            >
              配置
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="left" label="服务能力配置" min-width="150">
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="goTocapability(scope.row.ServiceId)"
            >
              配置
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
                icon="edit"
                type="primary"
                link
                @click="openDetailDialog(scope.row)"
            >编辑</el-button
            >
            <el-button
                icon="delete"
                type="primary"
                link
                @click="deleteService(scope.row)"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer
        v-model="detailDialog"
        size="60%"
        :show-close="false"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
    >
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">服务代理详情</span>
          <div>
            <el-button @click="closeDetailDialog">取消</el-button>
            <el-button type="primary" v-show="flagS" @click="submitDetailForm"
            >确定</el-button
            >
            <el-button type="primary" v-show="flagU" @click="updateDetailForm"
            >保存</el-button
            >
          </div>
        </div>
      </template>
      <el-form
          ref="detailForm"
          :rules="rules"
          :model="serviceInfo"
          label-width="120px"
      >
        <el-form-item label="服务代理名称" prop="ServiceName">
          <el-input v-model="serviceInfo.ServiceName" />
        </el-form-item>
        <el-form-item label="代理类别" prop="ServiceType">
          <el-select
              v-model="serviceInfo.ServiceType"
              placeholder="请选择代理类别"
              style="width: 100%"
              @change="change"
          >
            <el-option label="水印" :value="'水印'" />
            <el-option label="智能" :value="'智能'" />
            <el-option label="授权" :value="'授权'" />
          </el-select>
        </el-form-item>

        <el-form-item label="程序url" prop="VisitUrl">
          <el-input v-model="serviceInfo.VisitUrl" />
        </el-form-item>
        <el-form-item label="运行路径" prop="ServiceExecDir">
          <el-input v-model="serviceInfo.ServiceExecDir" />
        </el-form-item>
        <el-form-item label="程序版本号" prop="ServiceVersion">
          <el-input v-model="serviceInfo.ServiceVersion" />
        </el-form-item>


      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import {
  getServiceList,
  addServices,
  deleteServices,
  updateServices,
} from "@/api/service";

const router = useRouter();
const flagS = ref(false);
const flagU = ref(false);
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const sortInfo = ref({ prop: "", order: "" });
const searchInfo = ref({ serviceName: "" });

const tableData = ref([]);

const filteredData = computed(() => {
  const filterValue = searchInfo.value.serviceName.toLowerCase();
  return (tableData.value || []).filter((item) =>
      item.ServiceName.toLowerCase().includes(filterValue)
  );
});

const sortedData = computed(() => {
  const data = [...filteredData.value];
  if (sortInfo.value.prop && sortInfo.value.order) {
    data.sort((a, b) => {
      let aValue = a[sortInfo.value.prop];
      let bValue = b[sortInfo.value.prop];
      if (sortInfo.value.prop === "UpdatedAt") {
        aValue = new Date(aValue).getTime();
        bValue = new Date(bValue).getTime();
      } else if (sortInfo.value.prop === "CreatedAt") {
        aValue = parseInt(aValue);
        bValue = parseInt(bValue);
      }
      if (sortInfo.value.order === "ascending") {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });
  }
  return data;
});

const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};

const handleCurrentChange = (val) => {
  page.value = val;
  getTableData();
};

const getTableData = async () => {
  try {
    const response = await getServiceList(page.value, pageSize.value);
    tableData.value = response.data.list;
    total.value = response.data.total;
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取数据失败");
  }
};

getTableData();

const onSubmit = () => {
  getTableData();
};

const onReset = () => {
  searchInfo.value.serviceName = "";
  getTableData();
};

const detailDialog = ref(false);
const serviceInfo = ref({
  ServiceName: "",
  ServiceId: "",
  ServiceType: "",
  ServiceVersion: "v1",
  Status: "1", // 默认状态设置为正常
  UpdatedAt: "",
  CreatedAt: "",
  ServiceExecDir: "",
  NodeID: "",
});

const rules = ref({
  ServiceName: [{ required: true, message: "请输入服务代理名称", trigger: "blur" }],
  ServiceId: [{ required: true, message: "请输入服务ID", trigger: "blur" }],
  ServiceType: [{ required: true, message: "请选择代理类别", trigger: "change" }],
  Status: [{ required: true, message: "请选择状态", trigger: "change" }],
  VisitUrl: [{ required: true, message: "请输入访问URL", trigger: "blur" }],
  ServiceExecDir: [{ required: true, message: "请输入运行路径", trigger: "blur" }],
  NodeID: [{ required: true, message: "请输入服务代理", trigger: "blur" }],
});

const change = (value) => {
  console.log("Selected Value: ", value);
};

const openDetailDialog = (row) => {
  serviceInfo.value = { ...row };
  flagS.value = false;
  flagU.value = true;
  detailDialog.value = true;
};

const closeDetailDialog = () => {
  detailDialog.value = false;
};

const addService = () => {
  serviceInfo.value = {
    ServiceName: "",
    ServiceType: "",
    Status: "1",
    VisitUrl: "",
    ServiceExecDir: "",
    NodeID: "",
  };
  flagS.value = true;
  flagU.value = false;
  detailDialog.value = true;
};

const deleteService = (row) => {
  ElMessageBox.confirm(
      `确认删除服务代理【${row.ServiceName}】吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
  )
      .then(async () => {
        try {
          let param = ''; // 使用 let 声明
          console.log('appid is there:', row.ServiceId);
          param = row.ServiceId;
          await deleteServices({"ServiceId":param});
          ElMessage.success("删除成功");
          getTableData();
        } catch (error) {
          console.error("API Error:", error);
          ElMessage.error("删除失败");
        }
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
};

const submitDetailForm = async () => {
  try {
    await addServices(serviceInfo.value);
    ElMessage.success("新增成功");
    detailDialog.value = false;
    getTableData();
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("新增失败");
  }
};

const updateDetailForm = async () => {
  try {
    await updateServices(serviceInfo.value);
    ElMessage.success("更新成功");
    detailDialog.value = false;
    getTableData();
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("更新失败");
  }
};

const goToconfigure = (ServiceId) => {
  router.push({ path: "./configure", query: { ServiceId } });
};
const goTocapability = (ServiceId) => {
  router.push({ path: "./capability", query: { ServiceId } });
};

</script>

<style scoped>
.gva-search-box {
  margin-bottom: 20px;
}

.gva-btn-list {
  margin-bottom: 20px;
}

.gva-pagination {
  margin-top: 20px;
}
</style>
